package flyingpig.servlet;


import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.HibernateException;
import org.hibernate.Transaction;

import flyingpig.data.dao.JobPageHome;
import flyingpig.data.dao.SearchJobHome;
import flyingpig.data.domain.JobPage;
import flyingpig.data.domain.SearchJob;
import flyingpig.hibernate.HibernateUtil;

import java.util.Date;

/**
 * Servlet implementation class MyServlet
 */
public class GenerateJob extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * Default constructor. 
     */
    public GenerateJob() {
        // TODO Auto-generated constructor stub
    	super();
    }
    
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html");

		PrintWriter out = response.getWriter();
		String concept = request.getParameter("concept");
		String sTotal = request.getParameter("total");
		String sPageCapacity = request.getParameter("pageCapacity");
		String source = request.getParameter("source");
		int total = Integer.parseInt(sTotal);
		int pageCapacity = Integer.parseInt(sPageCapacity);

		SearchJob searchJob = new SearchJob(concept, total, pageCapacity, 0,
				source, "INCOMPLETE", new Date());
		
		
		Transaction tx = HibernateUtil.getCurrentSession().beginTransaction();
		
		try {
				generateJobPage(searchJob);
				out.println("success");
				out.println("new Job id: ");
				out.println(searchJob.getSearchJobId());
			
			tx.commit();		

		} catch (HibernateException e) {

			tx.rollback();
			out.println("failed.");
			e.printStackTrace();
		} finally {

			out.flush();
			out.close();
		}
	}
	
	private void generateJobPage(SearchJob searchJob){
		SearchJobHome searchJobHomedao = new SearchJobHome();
		JobPageHome jobPageDao = new JobPageHome();

		searchJobHomedao.persist(searchJob);

		int pages = searchJob.getTotal();
		for(int i=1;i<=pages;i++){
			JobPage page = new JobPage(i,"INCOMPLETE",searchJob.getSearchJobId(),0,"",new Date());
			jobPageDao.persist(page);
		}
	}
}
